package com.dzf.controller;

import com.dzf.entity.*;
import com.dzf.mapper.CartMapper;
import com.dzf.service.CartService;
import com.dzf.service.LargeFileService;
import com.dzf.service.OrdService;
import com.dzf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@RequestMapping("/api/fore")
@RestController
public class ForeController {
    @Autowired
    CartService cartService;
    @Autowired
    OrdService ordService;
    @Autowired
    PublicController publicController;
    @Autowired
    UserService userService;
    @Autowired
    LargeFileService largeFileService;

    @RequestMapping("/findAll")
    public RespJson findAll()
    {
        MyUser user = (MyUser) publicController.getUser();
        if (user.getId()==0)
        {
            return RespJson.pack(401,"未登录！",null);
        }
        return RespJson.pack(200,"OK",cartService.findAll(user.getId()));
    }

    @RequestMapping("/cart/deleteMyCart")
    public RespJson deleteMyCart(@RequestBody Map<String,Object> map){
        MyUser user = (MyUser) publicController.getUser();
        cartService.deleteMyCart((List<Object>) map.get("bookid"),user.getId());
        return RespJson.pack(200,"添加成功",null);
    }

    @RequestMapping("/cart/addCart")
    public RespJson addCart(@RequestBody Cart cart){
        MyUser user = (MyUser) publicController.getUser();
        cart.setUid(user.getId());
        cart.setTcreate(new Date());
        cart.setNum(1);
        System.err.println(cart);
        cartService.updCart(cart);
        return RespJson.pack(200,"添加成功",null);
    }

    @RequestMapping("/ord/findItemInfoByOrdid/{ordid}")
    public RespJson findItemInfoByOrdid(@PathVariable("ordid") int ordid){
        List<ItemBook> itemBooks = ordService.findItemInfoByOrdid(ordid);
        return RespJson.pack(200,"OK",itemBooks);
    }



    //前端后端
    @RequestMapping("/ord/findInfoByOrdid/{ordid}")
    public RespJson findInfoByOrdid(@PathVariable("ordid")int ordid)
    {
        MyUser user = (MyUser) publicController.getUser();
        OrdInfo info = ordService.findInfoByOrdid(user.getId(), ordid);
        System.err.println(info);
        return RespJson.pack(200,"ok",info);
    }

    @RequestMapping("/ord/addAddr")
    public RespJson addAddr(@RequestBody Order order)
    {
        ordService.addAddr(order);
        return RespJson.pack(200,"OK","");
    }

    @Transactional
    @RequestMapping("/cart/addCart2Order")
    public RespJson addCart2Order(@RequestBody List<Cart> carts)
    {
        int sum = 0;
//        System.err.println(carts);
        for (Cart cart:carts) {
//            System.err.println(cart);
            sum += (cart.getNum()*cart.getBook().getPrice());
        }//把总价算出。amount
        MyUser user = (MyUser) publicController.getUser();

        Order ord = new Order();
        ord.setUid(user.getId());
        ord.setIspay(0);
        ord.setPhone(user.getPhone());
        ord.setAmount(sum);
        ord.setTcreate(new Date());


        OrdInfo ordInfo = ordService.addOrdItem(user, ord, carts);//涉及多条sql操作，放在service层做具体实现
        return RespJson.pack(200,"ok",ordInfo);
    }

    @RequestMapping("/ord/addPay")
    public RespJson addPay(Order ord){
        ordService.addPay(ord);
        return RespJson.pack(200,"OK",null);
    }

    //前端接口
    @RequestMapping("/cart/findOrdLines")
    public RespJson findOrdLines(@RequestBody Map<String,Object> map)
    {
        List<OrderLine> list = ordService.findOrdLines(map);
        return RespJson.pack(200,"ok",list);
    }

    @RequestMapping("/cart/findOrdLineByPage/{start}/{num}")
    public RespJson findOrdLineByPage(@RequestBody Map<String,Object> map,@PathVariable("start") int start,@PathVariable("num")int num)
    {
        map.put("start",(start*num)-num);
        map.put("num",num);

        //将数组结果和总行数封装后返回出来
        Map<String, Object> resultmap = ordService.findOrdInfo(map);
        return RespJson.pack(200,"ok",resultmap);
    }


    //用户
    @PostMapping("/user/updatePwd")
    public RespJson updatePwd(String password)
    {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //获取用户后将密码给用户
        MyUser user = (MyUser) publicController.getUser();
        user.setPassword(encoder.encode(password));
        userService.updatePwd(user);
        return RespJson.pack(200,"修改密码成功",null);
    }

    @RequestMapping("/user/updateImg")
    public RespJson updateImg(@RequestParam(value = "img",required = false) MultipartFile img)
    {
        //得到当前登录用户
        MyUser user = (MyUser) publicController.getUser();
        String uuid = userService.updateImg(user, img);//业务结束后把uuid返回
        return RespJson.pack(200,"更新用户头像成功",uuid.toString().replace("-",""));
    }

    @RequestMapping("/user/updateInfo")
    public RespJson updateInfo(String nickname,String phone)
    {
        MyUser user = (MyUser) publicController.getUser();
        user.setNickname(nickname);
        user.setPhone(phone);
        System.err.println(user);
        userService.updateInfo(user);
        return RespJson.pack(200,"OK",null);
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }
}
